import { useState, useEffect } from 'react'
import { convertToRaw, EditorState, ContentState } from 'draft-js';
import { Editor } from "react-draft-wysiwyg";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';

// 依赖下载有冲突使用npm i --legacy-peer-deps
export default function MyEditor(props) {
    const [editorState, setEditorState] = useState('')
    const onEditorStateChange = (e) => {
        setEditorState(e)
    }

    //必须在失去焦点的时候设置获取内容否则报错
    const getDraft = () => {
        const content = draftToHtml(convertToRaw(editorState.getCurrentContent()))
        props.getNewsContent(content)
    }


    useEffect(() => {
        if (props.content) {
            let str = ''
            try {
                str = JSON.parse(props.content)
            } catch {
                str = props.content
            }
            const html = htmlToDraft(str)
            const contentState = ContentState.createFromBlockArray(html.contentBlocks)
            const editorState = EditorState.createWithContent(contentState)
            setEditorState(editorState)
        }
    }, [props.content])

    return (
        <Editor
            editorState={editorState}
            toolbarClassName="toolbarClassName"
            wrapperClassName="wrapperClassName"
            editorClassName="editorClassName"
            onEditorStateChange={(e) => onEditorStateChange(e)}
            onBlur={getDraft}
        />
    )
}
